<template>
  <div>
    <el-dialog width="720px" :title="formInfo[convertType].title || ''" :visible="dialogVisible" :show-close="false"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <!-- <pre>{{supplier}}</pre> -->
      <el-form :model="form" ref="dialogForm">
        <el-form-item v-if="convertType === '20' && !isReport" label="搜索供应商:" :label-width="formLabelWidth">
          <el-input v-model="form.supplierName" placeholder="请选择供应商" @focus="supplierDialogVisible = true" readonly>
            <el-button slot="append" icon="el-icon-search" @click="supplierDialogVisible = true"></el-button>
          </el-input>
        </el-form-item>
        <el-row v-else>
          <el-col :span="8">
            <el-form-item label="供应商代码:" :label-width="formLabelWidth">
              {{ supplier.supplierCode }}
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="供应商名称:" :label-width="formLabelWidth">
              {{ supplier.supplierName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="convertType !== '30'" :label="`${formInfo[convertType].reasonLabel}:`"
          :label-width="formLabelWidth">
          <el-select v-model="form.reason" :placeholder="`请选择${formInfo[convertType].reasonLabel}`" style="width:100%">
            <el-option v-for="(item, key) in formInfo[convertType].reasons" :key="key" :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="`${formInfo[convertType].remarkLabel}:`" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="form.reasonDescription"
            :placeholder="`请输入${formInfo[convertType].remarkLabel}`" maxlength="200" :autosize="{ minRows: 10 }"
            :show-word-limit="true" />
          <p>注：{{ formInfo[convertType].remarkLabel }}长度在200个字以内；</p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">提交审核</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-dialog>
    <SelectSupplierDialog :supplierVisible.sync="supplierDialogVisible" @handle-select="handleGetSupplierInfo" />
  </div>
</template>

<script>
import { mapMutations } from 'vuex';
import SelectSupplierDialog from '@/pages/supplier/components/SelectSupplierDialog.vue'
import { convertSupplierReasons } from '../constants/';
// 黑名单
import {
  addBlacklistSupplier,
  activateBlacklistSupplier
} from '@/api/supplier/management/supplierBlacklist'
// 淘汰
import {
  addEliminateSupplier,
  activateEliminateSupplier
} from '@/api/supplier/management/eliminateSupplier'
const {
  INITIAL_FIELDS_VALUE,
  CONVERT_FORM_INFO,
} = convertSupplierReasons

export default {
  name: 'ConvertSupplierDialog',
  components: {
    SelectSupplierDialog
  },
  props: {
    dialogVisible: {
      // 弹框显隐
      type: Boolean,
      default: false
    },
    convertType: {
      // 弹框类型
      // 1: 线索转潜在 2: 线索转合格
      // 3: 潜在转线索 4: 潜在转合格
      // 5: 合格转潜在
      // 6: 淘汰 7：淘汰激活 8：黑名单 9：黑名单激活
      // 30: 编辑合格供应商潜在供应商
      type: String,
      default: '1'
    },
    supplier: {
      // 弹框数据：供应商
      type: Object,
      default () {
        return {};
      }
    },
    // 考察报告
    isReport: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      supplierDialogVisible: false,
      formLabelWidth: '120px',
      form: Object.assign({}, INITIAL_FIELDS_VALUE),
      formInfo: CONVERT_FORM_INFO,
      pickedSupplier: {},
      loading: false,
    }
  },
  watch: {
    dialogVisible: {
      immediate: true,
      handler (newVal, oldVal) {
        if (newVal && newVal !== oldVal) {
          this.updateLoadingState()
        }
      }
    }
  },
  methods: {
    ...mapMutations('supplier/baseList', [
      'setFormItemData',
    ]),
    // 获取供应商信息
    handleGetSupplierInfo (row) {
      const {
        supplierName, // 供应商编码
        // supplierCode, // 供应商编码
        // supplierId, // 供应商id
        // supplierClassify, // 供应商分类
        // supplierClassifyName, // 供应商分类
        // supplierNature, // 供应商性质
        // supplierNatureName, // 供应商性质
        // registerAddress, // 详细地址
      } = row;
      this.pickedSupplier = row
      this.form.supplierName = supplierName
    },
    async handleSubmit () {
      const { form, formInfo, convertType, supplier, pickedSupplier } = this
      const { reason, reasonDescription } = form
      const params = {
        reason,
        reasonDescription,
        supplierCode: supplier.supplierCode || pickedSupplier.supplierCode,
        supplierId: supplier.supplierId || pickedSupplier.supplierId,
        backlogId: supplier.backlogId || pickedSupplier.backlogId
      }
      const { reasons, reasonLabel, remarkLabel } = formInfo[convertType]

      if (reasons && !reason) {
        this.$message.error(`请选择${reasonLabel}`)
        return false;
      }
      const selectedItem = reasons && reasons.find(i => i.value === reason)
      if (selectedItem && selectedItem.label === '其他' && !reasonDescription) {
        this.$message.error(`请输入${remarkLabel}`)
        return false;
      }
      if (!params.supplierCode || !params.supplierId) {
        this.$message.error('请选择供应商')
        return false;
      }
      if (!params.reasonDescription) {
        this.$message.error(`请输入${remarkLabel}`)
        return false;
      }
      this.loading = true
      // 1: 线索转潜在 2: 线索转合格
      // 3: 潜在转线索 4: 潜在转合格
      // 5: 合格转潜在
      if (['1', '2', '4', '30'].includes(this.convertType)) {
        // 跳转转化供应商
        this.supplier.causeType = reason
        this.supplier.causeDescription = reasonDescription
        this.$emit('update:supplier', this.supplier)
        this.close(1)
      } else if (['3', '5'].includes(this.convertType)) {
        // 直接转化供应商
        this.supplier.causeType = reason
        this.supplier.causeDescription = reasonDescription
        this.submit(this.supplier)
      } else {
        // 淘汰 黑名单this.loading = true
        const resp = await this.request(params)
        this.loading = false
        if (resp && resp.status === '0') {
          this.showMessage()
          this.close(resp)
        }
      }
    },
    request (params) {
      // 10: 淘汰
      // 11：淘汰激活 - 线索激活 12: 淘汰激活 - 潜在激活 13: 淘汰激活 - 合格激活
      // 20：黑名单
      // 21：黑名单激活 - 潜在激活 22: 黑名单激活 - 合格激活
      const isQualified = this.supplier.supplierClassify === 40332
      const isSpecial = [1005, 1006, 1008, 1010].includes(this.supplier.supplierType)
      switch (this.convertType) {
        case '10':
          if (isQualified) {
            // 合格供应商
            params.processDocumentOperateType = 25
          } else if (isSpecial) {
            // 特殊供应商
            params.processDocumentOperateType = 27
          } else {
            params.processDocumentOperateType = 10
          }
          return addEliminateSupplier(params)
        case '11':
        case '12':
        case '13':
          if (isQualified) {
            // 合格供应商
            params.processDocumentOperateType = 26
          } else if (isSpecial) {
            // 特殊供应商
            params.processDocumentOperateType = 28
          } else {
            params.processDocumentOperateType = 11
          }
          return activateEliminateSupplier(params)
        case '20':
          return addBlacklistSupplier(params)
        case '21':
        case '22':
          return activateBlacklistSupplier(params)
      }
    },
    showMessage () {
      // 10: 淘汰
      // 11：淘汰激活 - 线索激活 12: 淘汰激活 - 潜在激活 13: 淘汰激活 - 合格激活
      // 20：黑名单
      // 21：黑名单激活 - 潜在激活 22: 黑名单激活 - 合格激活
      switch (this.convertType) {
        case '10':
          this.$message.success('操作成功')
          break
        case '11':
        case '12':
        case '13':
          // this.$message.success('已提交审批：淘汰供应商激活')
          break
        case '20':
          // this.$message.success('已提交审批：添加黑名单供应商')
          break
        case '21':
        case '22':
          // this.$message.success('已提交审批：黑名单供应商激活')
          break
      }
    },
    handleCancel () {
      this.close()
    },
    updateLoadingState (state = false) {
      this.loading = state
    },
    close (data) {
      this.$refs.dialogForm.resetFields()
      this.form = Object.assign({}, INITIAL_FIELDS_VALUE)
      this.$emit('handleClose', data)
    },
    submit (data) {
      this.$emit('handleSubmit', data)
    }
  },
  beforeRouteEnter (to, from, next) {
    // 保存入口地址
    next((vm) => {
      vm.fromPageName = from.name
    })
  },
  beforeRouteLeave (to, from, next) {
    // 如果不是正常返回清空列表页面查询表单字段
    if (this.fromPageName !== to.name) {
      this.setFormItemData(null);
    }
    next()
  }
}
</script>

<style scoped>
.convert-supplier-dialog {
  width: 640px;
}
</style>
